package com.thinkverse.user.controller;

import com.thinkverse.user.dto.ApiResponse;
import com.thinkverse.user.dto.AuditRequest;
import com.thinkverse.user.dto.PageRequest;
import com.thinkverse.user.dto.PagedResult;
import com.thinkverse.user.entity.IdentityClaim;
import com.thinkverse.user.service.IdentityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 管理员接口（身份认证审核）
 * 注意：方法中没有做角色校验，建议你在网关或本服务增加 RBAC 校验（检查 X-USER-ID 对应用户是否为 ADMIN）
 */
@RestController
@RequestMapping("/admin/identity")
@Tag(name = "管理员-科研认证")
@RequiredArgsConstructor
public class AdminIdentityController {

    private final IdentityService identityService;

    private Long resolveUserId(HttpServletRequest req) {
        String idStr = req.getHeader("X-USER-ID");
        if (idStr == null || idStr.isBlank()) throw new RuntimeException("请先登录");
        return Long.valueOf(idStr);
    }

    @GetMapping("/claims")
    @Operation(summary = "管理员查看所有认证申请")
    public ApiResponse<PagedResult<IdentityClaim>> listAll(@Valid PageRequest pageReq) {
        PagedResult<IdentityClaim> res = identityService.listAllClaims(pageReq.getPage(), pageReq.getSize());
        return ApiResponse.success(res);
    }

    @PutMapping("/claims/{id}/audit")
    @Operation(summary = "管理员审核申请")
    public ApiResponse<Object> auditClaim(HttpServletRequest req, @PathVariable("id") Long id, @Valid @RequestBody AuditRequest auditRequest) {
        Long adminUserId = resolveUserId(req);
        identityService.auditClaim(adminUserId, id, auditRequest.getAuditStatus(), auditRequest.getAuditMessage());
        return ApiResponse.success(Map.of("userRoleUpdated", "APPROVED".equalsIgnoreCase(auditRequest.getAuditStatus())));
    }
}
